/**
 * LockboxTableCell
 * Secret Item Table Cell class
 *
 * Created by Nathan Black
 */
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import <WebCore/WebFontCache.h>
#import <GraphicsServices/GraphicsServices.h>
#import "LockboxItem.h"
#import "LockboxTableCell.h"
#import "LockboxOptions.h"


// since objc doesn't have class variables.... sigh... I miss .NET
/*CGColorRef LBG_transparent = NULL;
struct __GSFont *LBG_bigBoldFont = NULL;
struct __GSFont *LBG_normalFont = NULL;*/

@interface LockboxTableCell (Private)

- (void)disclosurePressed;
- (void)transToItemView:(LockboxItem*)item cell:(LockboxTableCell*)cell;
- (void)setupUI;

@end

@implementation LockboxTableCell

+ (CGColorRef)colorWithRed:(float)red green:(float)green blue:(float)blue alpha:(float)alpha
{
    float rgba[4] = {red, green, blue, alpha};
    CGColorRef color = (CGColorRef)[(id)CGColorCreate((CGColorSpaceRef)[(id)CGColorSpaceCreateDeviceRGB() autorelease], rgba) autorelease];
    return color;
}

+ (NSString*)maskedStringFrom:(NSString*)str
{
    // This looks bad, but it's quick and secure, taking advantage of that we want to limit the string length anyways.
    //char* mask = "******************************"; - why doesn't this work? odd.
    char mask[] = { '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', 0};
    
    if ([str length] < 25) {
        mask[[str length]] = '\0';
    }
    //NSLog(@"mask is %s", mask);
    return [[[NSString alloc] initWithUTF8String:mask] autorelease];
}

- initWithFrame:(struct CGRect)frame;
{
    self = [super initWithFrame:frame];
    if (self)
    {
        [self setShowDisclosure: YES];
        [self setDisclosureClickable: YES];
        [self setDisclosureStyle: 0];
        [[self _disclosureView] addTarget:self action:@selector(disclosurePressed) forEvents:3 /* mouse down */];
        [self setTapDelegate:self];
    }
    return self;
}

- (void)deallocFields
{
    [_keyLabel release];
    _keyLabel = NULL;
    [_valueLabel release];
    _valueLabel = NULL;
    [_websiteLabel release];
    _websiteLabel = NULL;
    [_expDateLabel release];
    _expDateLabel = NULL;
}

- (void)dealloc
{
    [self deallocFields];

    [super dealloc];
}

- (void)setItem:(LockboxItem *)newItem
{
    _item = newItem;

    /*NSLog(@"setItem: item: 0x%x", _item);
    NSLog(@"setItem: key: %@", _item->key);
    NSLog(@"setItem: value: %@", _item->value);
    NSLog(@"setItem: website: %@", _item->website);
    NSLog(@"setItem: expDate: %@", _item->expDate);
    NSLog(@"setItem: type: %d", _item->type);*/
    [self refresh];
}

- (void)refresh
{
    [self setupUI];
    
    BOOL bMask = ![[LockboxOptions globalInstance] showSecretInList];

    [_keyLabel setText:_item->key];
    [_valueLabel setText:(bMask ? [LockboxTableCell maskedStringFrom:_item->value] : _item->value)];
    switch (_item->type) {
        case LBI_PASSWORD:
            [_websiteLabel setText:_item->website];
            break;
        case LBI_CARD:
            [_expDateLabel setText:(bMask ? [LockboxTableCell maskedStringFrom:_item->expDate] : _item->expDate)];
            break;
    }
}

- (void)setupUI
{
    //if (LBG_transparent == NULL) LBG_transparent = [LockboxTableCell colorWithRed:0.0f green:0.0f blue:0.0f alpha:0.0];
    //if (LBG_bigBoldFont == NULL) LBG_bigBoldFont = [NSClassFromString(@"WebFontCache") createFontWithFamily:@"Helvetica" traits:2 size:18.0f];
    //if (LBG_normalFont == NULL) LBG_normalFont = [NSClassFromString(@"WebFontCache") createFontWithFamily:@"Helvetica" traits:0 size:16.0f];
    CGColorRef LBG_transparent = [LockboxTableCell colorWithRed:0.0f green:0.0f blue:0.0f alpha:0.0];
    struct __GSFont *LBG_bigBoldFont = [NSClassFromString(@"WebFontCache") createFontWithFamily:@"Helvetica" traits:2 size:18.0f];
    struct __GSFont *LBG_normalFont = [NSClassFromString(@"WebFontCache") createFontWithFamily:@"Helvetica" traits:0 size:16.0f];
    
    [_keyLabel removeFromSuperview];
    [_valueLabel removeFromSuperview];
    [_websiteLabel removeFromSuperview];
    [_expDateLabel removeFromSuperview];
    [self deallocFields];

    float rMargin = [self disclosureRightMargin]; 
    switch (_item->type) {
        case LBI_OTHER:
            // TODO: Query the font height for acurate measurments
            _keyLabel = [[UITextLabel alloc] initWithFrame:CGRectMake(LTC_MARGIN_X, LTC_MARGIN_Y, LTC_ROWWIDTH - rMargin, 20.0f)];
            [_keyLabel setBackgroundColor:LBG_transparent];
            [_keyLabel setFont:LBG_bigBoldFont];

            _valueLabel = [[UITextLabel alloc] initWithFrame:CGRectMake(LTC_MARGIN_X + LTC_VALOFFSET_X, LTC_MARGIN_Y + LTC_VALOFFSET_Y, LTC_ROWWIDTH - LTC_VALOFFSET_X - rMargin, 20.0f)];
            [_valueLabel setBackgroundColor:LBG_transparent];
            [_valueLabel setFont:LBG_normalFont];
            break;
            
        case LBI_PASSWORD:
            _websiteLabel = [[UITextLabel alloc] initWithFrame:CGRectMake(LTC_MARGIN_X, LTC_MARGIN_Y, LTC_ROWWIDTH - rMargin, 20.0f)];
            [_websiteLabel setBackgroundColor:LBG_transparent];
            [_websiteLabel setFont:LBG_bigBoldFont];
            [_websiteLabel setWrapsText:NO];
            [self addSubview:_websiteLabel];

            _keyLabel = [[UITextLabel alloc] initWithFrame:CGRectMake(LTC_MARGIN_X, LTC_MARGIN_Y + LTC_PWOFFSET_Y, LTC_PWOFFSET_X - LTC_MARGIN_X, 20.0f)];
            [_keyLabel setBackgroundColor:LBG_transparent];
            [_keyLabel setFont:LBG_normalFont];

            _valueLabel = [[UITextLabel alloc] initWithFrame:CGRectMake(LTC_MARGIN_X + LTC_PWOFFSET_X, LTC_MARGIN_Y + LTC_PWOFFSET_Y, 
                                LTC_ROWWIDTH - LTC_PWOFFSET_X - LTC_MARGIN_X - rMargin, 20.0f)];
            [_valueLabel setBackgroundColor:LBG_transparent];
            [_valueLabel setFont:LBG_normalFont];
            break;
            
        case LBI_CARD:
            _keyLabel = [[UITextLabel alloc] initWithFrame:CGRectMake(LTC_MARGIN_X, LTC_MARGIN_Y, LTC_ROWWIDTH - rMargin, 20.0f)];
            [_keyLabel setBackgroundColor:LBG_transparent];
            [_keyLabel setFont:LBG_bigBoldFont];

            _valueLabel = [[UITextLabel alloc] initWithFrame:CGRectMake(LTC_MARGIN_X, LTC_MARGIN_Y + LTC_CARDOFFSET_Y, LTC_CARDOFFSET_X - LTC_MARGIN_X, 20.0f)];
            [_valueLabel setBackgroundColor:LBG_transparent];
            [_valueLabel setFont:LBG_normalFont];

            _expDateLabel = [[UITextLabel alloc] initWithFrame:CGRectMake(LTC_MARGIN_X + LTC_CARDOFFSET_X, LTC_MARGIN_Y + LTC_CARDOFFSET_Y, 
                                LTC_ROWWIDTH - LTC_CARDOFFSET_X - LTC_MARGIN_X - rMargin, 20.0f)];
            [_expDateLabel setBackgroundColor:LBG_transparent];
            [_expDateLabel setFont:LBG_normalFont];
            [_expDateLabel setWrapsText:NO];
            [self addSubview:_expDateLabel];
            break;
    }

    [_keyLabel setWrapsText:NO];
    //[_keyLabel setEllipsisStyle: 2];
    [self addSubview:_keyLabel];

    [_valueLabel setWrapsText:NO];
    //[_keyLabel setEllipsisStyle:2];
    [self addSubview:_valueLabel];
}

///////////////// Delegates //////////////////////
- (BOOL)view:(id)view handleTapWithCount:(int)count event:(struct __GSEvent *)event
{
    //CGPoint p = [self convertPoint: GSEventGetLocationInWindow(event) fromView: nil];

    //NSLog(@"point x:%3.1f y:%3.1f", p.x, p.y);
    //NSLog(@"point inside? %d", [[self _disclosureView] pointInside:p forEvent:event]);
    return YES;
}

/*- (void)removeControlWillShowRemoveButton:(id)removeId animated:(BOOL)animated
{
    NSLog(@"removeControlWillShowRemoveButton: id %@ animated: %d", removeId, animated);
    if (removeId == NULL) {
        [self addSubview:[self createRemoveControl]];
    }
    else {
        [self addSubview:removeId];
    };
}*/

- (void)setDelegate:(id)object
{
    _delegate = object;
}

- (BOOL)ignoresMouseEvents 
{
    return NO; 
}

- (void)mouseUp:(struct __GSEvent*)event 
{
    if ([[LockboxOptions globalInstance] selectToEdit]) {
        [self disclosurePressed];
    }

    if ([super respondsToSelector:@selector(mouseUp:)])
    {
        [super mouseUp:event];
    }
}

- (void)disclosurePressed
{
    if (_delegate != nil && [_delegate respondsToSelector:@selector(transToItemView:cell:)])
    {
        [_delegate transToItemView:_item cell:self];
    }
}

/*- (NSMethodSignature*)methodSignatureForSelector:(SEL)selector {
 NSLog(@"LBTableCell: Requested method for selector: %@", NSStringFromSelector(selector));
 return [super methodSignatureForSelector:selector];
}

- (BOOL)respondsToSelector:(SEL)aSelector {
NSLog(@"LBTableCell: Request for selector: %@", NSStringFromSelector(aSelector));
return [super respondsToSelector:aSelector];
}

- (void)forwardInvocation:(NSInvocation *)anInvocation {
 NSLog(@"LBTableCell: Called from: %@", NSStringFromSelector([anInvocation selector]));
[super forwardInvocation:anInvocation];
}*/

@end
